#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <getopt.h>

#include "server.h"
#include "database.h"
#include "login.h"
#include "smtp.h"
#include "pop3.h"
#define DATA_BASE_PATH "/home/zhangbing/data/email.db"
int main()
{
    /* Configuration */
    int login_port = 1000;
    int smtp_port = 2000;
    int pop3_port = 3000;
    char *dbfile = DATA_BASE_PATH;

    /* Ensure database works */
    struct database db;

    if (database_open(&db, dbfile) != 0)
        {
            DEBUG_PRINT("open database error : %s\r\n",dbfile);
	        DEBUG_PRINT("error code:%d \r\n message: %s \r\n",errno,strerror(errno));
        }
    database_close(&db);

    /* Launch servers. */
    struct server login = 
    {
        .port = login_port,
        .handler = login_handler,
        .arg = dbfile
    };
    struct server smtp = 
    {
        .port = smtp_port,
        .handler = smtp_handler,
        .arg = dbfile
    };
    struct server pop3 = 
    {
        .port = pop3_port,
        .handler = pop3_handler,
        .arg = dbfile
    };
    DEBUG_PRINT("start server\r\n");
    if (server_start(&login) != 0)
    {
        DEBUG_PRINT("start login error : %s\r\n",dbfile);
	    DEBUG_PRINT("error code:%d \r\n message: %s \r\n",errno,strerror(errno));
    }
        

    if (server_start(&smtp) != 0)
    {
        DEBUG_PRINT("start smtp error : %s\r\n",dbfile);
	    DEBUG_PRINT("error code:%d \r\n message: %s \r\n",errno,strerror(errno));
    }
        
    if (server_start(&pop3) != 0)
    {
        DEBUG_PRINT("start pop3 error : %s\r\n",dbfile);
	    DEBUG_PRINT("error code:%d \r\n message: %s \r\n",errno,strerror(errno));
    }
     pthread_join(login.thread, NULL);
    pthread_join(smtp.thread, NULL);
    pthread_join(pop3.thread, NULL);
    return 0;
}
